<?php

namespace App\Jobs;

use App\Constant\QueueKey;
use App\Facades\SamLogFacade;
use App\Models\LoanApply;
use App\Models\SettingLoan;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Class LoanRequestTimeOutJob
 * Description:授信申请成功3天后处理任务类
 * Author: Sam
 * DateTime: 2019/1/8 9:18
 * @package App\Jobs
 */
class LoanRequestTimeOutJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $loan;

    /**
     * LoanRequestTimeOutJob constructor.
     * @param UserLoanRequest $loan
     */
    public function __construct(UserLoanRequest $loan)
    {
        $this->loan = $loan;
    }

    /**
     * Description:任务处理
     * Author: Sam
     * DateTime: 2019/1/7 14:41
     * @throws Exception
     */
    public function handle()
    {
        SamLogFacade::debug("进入time_out队列");
        $loan = $this->loan;
        $loan_apply = LoanApply::where('loan_request_id',$loan->id)->first();
        if(!$loan_apply){
            SamLogFacade::debug("没找到放款申请,说明还没有申请放款");
            DB::beginTransaction();
            try{
                $loan->status = UserLoanRequest::STATUS_TIME_OUT;
                $loan->save();
                DB::commit();
                SamLogFacade::debug("授信成功记录【{$loan->id}】更改为超时状态成功");
            }
            catch (Exception $exception)
            {
                SamLogFacade::error("授信成功记录【{$loan->id}】更改为超时状态失败：{$exception->getMessage()}");
                DB::rollBack();
                return false;
            }
            $delay_time = SettingLoan::getReceiptTime();
            SamLogFacade::debug("时限2：{$delay_time['receipt_time_one']}");
            $real_delay_time = $delay_time['receipt_time_two'] - $delay_time['receipt_time_one'];
            LoanRequestRestartJob::dispatch($loan)->delay(now()->addDays($real_delay_time))->onQueue(QueueKey::QUEUE_LOAN_REQUEST_RESTART);
        }
    }
}
